package com.qqtop10.manager.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtop10.manager.model.Advertise;
import com.qqtop10.manager.model.Category;
import com.qqtop10.manager.model.Floor;
import com.qqtop10.manager.model.IntCategory;
import com.qqtop10.manager.model.PagingArgs;
import com.qqtop10.manager.model.Result;
import com.qqtop10.manager.model.temp.Goods;
import com.qqtop10.manager.service.AdvertiseService;
import com.qqtop10.manager.service.BuildHtmlService;
import com.qqtop10.manager.service.CategoryService;
import com.qqtop10.manager.service.FloorService;
import com.qqtop10.manager.service.GoodsService;
import com.qqtop10.manager.service.IntCategoryService;
import com.qqtop10.manager.utils.FolderPath;
import com.qqtop10.manager.utils.RandomUtils;
import com.qqtop10.manager.utils.UrlPath;

/**
 * 
 * @author Jovi
 * @date 2015年11月24日
 */
@RequestMapping("/manager/")
@Controller
public class BuildController extends BaseController {

	@Autowired
	private BuildHtmlService buildHtmlService;

	@Autowired
	@Qualifier("advertiseService")
	private AdvertiseService advertiseService;

	@Autowired
	@Qualifier("categoryService")
	private CategoryService categoryService;

	@Autowired
	@Qualifier("goodsService")
	private GoodsService goodsService;

	private List<Category> allCategory = null;

	@Autowired
	@Qualifier("intCategoryService")
	private IntCategoryService intCategoryService;

	@Autowired
	@Qualifier("floorService")
	private FloorService floorService;

	private static Map<String, String> map = new HashMap<>();

	/**
	 * 生成首页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("buildIndex.do")
	@ResponseBody
	public Result buildIndex(HttpServletRequest request, Integer[] floor, String[] categoryUuid, String[] goodsUuid) {

		Result result = null;
		Map<String, Object> root = null;
		Map<String, List<Category>> categoryNode = null;
		Map<String, List<Goods>> goodsNode = null;
		List<Advertise> adhdp = null;
		List<Advertise> adggdb = null;
		List<Advertise> adsyhf = null;
		Map<String, Map<String, List<Goods>>> fgoods = null;
		List<Goods> goodslist = null;

		// 每一楼最大的推荐分类数量
		final int floorCategoryMaxSize = 10;
		// 每一楼最大的商品数量
		final int floorGoodsMaxSize = 10;
		// 楼层高度（在楼层循环中用）
		int floorHeight = floor.length;
		// 分楼层的推荐分类
		List<String[]> floorCategoryList = new ArrayList<>();
		// 分楼层的推荐商品
		List<String[]> floorGoodsList = new ArrayList<>();
		// 推荐分类进行分层
		for (int i = 0; i < floorHeight; i++) {
			int from = i * floorCategoryMaxSize;
			int to = (floorCategoryMaxSize + (i * floorCategoryMaxSize));
			floorCategoryList.add(Arrays.copyOfRange(categoryUuid, from, to));
		}

		// 推荐商品进行分层
		for (int i = 0; i < floorHeight; i++) {
			int from = i * floorGoodsMaxSize;
			int to = (floorGoodsMaxSize + (i * floorGoodsMaxSize));
			floorGoodsList.add(Arrays.copyOfRange(goodsUuid, from, to));
		}

		// 保存楼层数据
		for (int i = 0; i < floorHeight; i++) {

			String[] categoryArr = floorCategoryList.get(i);
			String[] goodsArr = floorGoodsList.get(i);
			StringBuffer categoryStrBuf = new StringBuffer();
			StringBuffer goodsStrBuf = new StringBuffer();
			for (int k = 0; k < categoryArr.length; k++) {
				categoryStrBuf.append(categoryArr[k]);
				// 如果循环变量k没到最后一个，则每个分类后面都加一个逗号
				if (k != categoryArr.length - 1) {
					categoryStrBuf.append(",");
				}
			}
			for (int k = 0; k < goodsArr.length; k++) {
				goodsStrBuf.append(goodsArr[k]);
				// 如果循环变量k没到最后一个，则每个商品后面都加一个逗号
				if (k != goodsArr.length - 1) {
					goodsStrBuf.append(",");
				}
			}

			// TODO 拿到每一个楼层的UUID，查询数据库中是否存在此UUID，若不存在则新增，反之则修改
			Floor floorData = new Floor();
			floorData.setFloor_id(i + 1);
			floorData.setUuid(RandomUtils.makeUUID());
			floorData.setFloor_category_uuid(categoryStrBuf.toString());
			floorData.setFloor_goods_uuid(goodsStrBuf.toString());
			Floor getFloor = floorService.selectFloorById(floorData.getFloor_id());
			if (getFloor != null) {
				floorService.updateFloor(floorData);
			} else {
				floorService.insertFloor(floorData);
			}
		}

		try {
			result = new Result(1, "生成首页成功");
			root = new HashMap<>();
			categoryNode = new HashMap<>();
			goodsNode = new HashMap<>();
			goodslist = new ArrayList<>();

			// TODO 接下来，根据每层楼的每个分类/商品的UUID查询对应的信息，并且生成首页
			// 查询每一层楼的推荐分类
			for (int i = 0; i < floorCategoryList.size(); i++) {
				String[] ret = floorCategoryList.get(i);
				List<Category> cList = new ArrayList<>(10);
				for (int k = 0; k < ret.length; k++) {
					// 如果当前位置没有选择推荐分类，则跳过，进行下一轮循环查询
					if (ret[k] == null || ret[k].length() != 32) {
						continue;
					}
					Category category = new Category();
					category.setUuid(ret[k]);
					cList.add(categoryService.get(category));
				}
				// category1 category2 category3
				categoryNode.put("category" + (i + 1), cList);
			}

			// 查询每一层的推荐商品
			for (int i = 0; i < floorGoodsList.size(); i++) {
				String[] ret = floorGoodsList.get(i);
				List<Goods> gList = new ArrayList<>(7);
				for (int k = 0; k < ret.length; k++) {
					if (ret[k] == null || ret[k].length() != 32) {
						continue;
					}
					Goods goods = goodsService.selectGoodsByUUID(ret[k]);
					goodslist.add(goods);
					gList.add(goods);
				}
				// goods1 goods2 goods3
				goodsNode.put("goods" + (i + 1), gList);
			}
			// 设置楼层商品以备静态输出
			fgoods = new HashMap<>();
			for (int i = 0; i < goodsNode.size(); i++) {
				List<Goods> goods = goodsNode.get("goods" + (i + 1));
				Map<String, List<Goods>> t = new HashMap<>();
				if (goods.size() > 0) {
					t.put("one", goods.subList(0, 1));
				}
				if (goods.size() > 1 && goods.size() <= 6) {
					t.put("two", goods.subList(1, goods.size()));
				} else if (goods.size() > 6) {
					t.put("two", goods.subList(1, 7));
				}
				if (goods.size() > 7 && goods.size() <= 10) {
					t.put("three", goods.subList(7, goods.size()));
				} else if (t.size() > 10) {
					t.put("three", goods.subList(7, 10));
				}
				// 添加商品推荐
				// fgoods1 fgoods2 fgoods3
				fgoods.put("fgoods" + (i + 1), t);
			}
			root.put("home", UrlPath.HOME);
			// 添加楼层
			root.put("floor", floor);
			// 添加楼层推荐
			root.put("fcategory", categoryNode);
			// 添加商品推荐
			root.put("fgoods", fgoods);
			// 幻灯片广告
			adhdp = getAdvertiseList(1);
			// 公告顶部广告
			adggdb = getAdvertiseList(2);
			// 首页横幅广告
			adsyhf = getAdvertiseList(3);
			root.put("adhdp", adhdp);
			root.put("goodslist", goodslist);
			root.put("adggdb", adggdb != null && adggdb.size() > 0 ? adggdb.get(0) : adggdb);
			root.put("adsyhf", adsyhf != null && adsyhf.size() > 0 ? adsyhf.get(0) : adsyhf);
			buildHtmlService.buildPage(null, "index.html", "index.html", root);
			this.buildClassMenu(request);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("生成首页失败：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 生成全球购
	 * 
	 * @param request
	 * @param categoryF1
	 * @return
	 */
	@RequestMapping("buildQuangqiugou.do")
	@ResponseBody
	public Result buildQuangqiugou(HttpServletRequest request) {
		Result result = null;
		Map<String, Object> map = null;
		Map<String, Object> root = null;
		StringBuffer from = null;
		StringBuffer where = null;
		List<Advertise> adsyhf = null;
		List<Category> categoryList = null;
		// 所有国家分类
		List<IntCategory> intCategoryList = null;
		// 各个商品分类下的商品列表
		Map<String, List<Object>> goodsMap = null;
		// 每个国家的所有商品分类下的商品map
		Map<String, Map<String, List<Object>>> icGoodsMap = null;
		// 每个国家的所有商品分类下的商品map
		Map<String, List<Category>> icCategoryMap = null;
		// 每个的国家分类键值对
		Map<String, String> icMap = null;
		try {
			result = new Result(1, "生成全球购成功");
			map = new HashMap<>();
			root = new HashMap<>();
			from = new StringBuffer();
			icGoodsMap = new LinkedHashMap<>();
			icCategoryMap = new LinkedHashMap<>();
			icMap = new LinkedHashMap<>();
			// 查询的商品列
			map.put("column",
					"tg.id,tg.uuid,tg.`name`,tg.attributes,tg.shop_uuid,tg.type,tg.`show`,tgd.price,tgd.stock,tgd.sold_quantity");
			// 默认来自这些表
			from.append("FROM tb_goods tg ");
			from.append("LEFT JOIN tb_goods_detailed tgd ON tg.uuid = tgd.goods_uuid");
			map.put("from", from.toString());
			Map<String, List<Object>> gjfl = new HashMap<>();
			// 获取全部国家列表
			intCategoryList = intCategoryService.selectAll();
			// 遍历全部国家分类
			
			for (IntCategory intCategory : intCategoryList) {
				icMap.put(intCategory.getUuid(), intCategory.getName());
				goodsMap = new HashMap<>();
				List<Object> tList = new ArrayList<>();
				// 每个国家的所有商品类型
				categoryList = categoryService.selectByIntCategoryUuid(intCategory.getUuid());
				// 储存每个国家的所有商品类型
				icCategoryMap.put(intCategory.getUuid(), categoryList);
				// 每个国家的每个类型商品只取最新的前8个
//				for (Category category : categoryList) {
					where = new StringBuffer();
					// 商品类型
//					where.append("WHERE tg.category_uuid = '" + category.getUuid() + "'");
					// 国家类型
					where.append(" WHERE tg.int_category_uuid = '" + intCategory.getUuid() + "'");
					// 必须是未删除的且上架的
					where.append(" AND tg.isdeleted = 0 AND tgd.isdeleted = 0 AND status = 1 AND tg.qqg_update_time IS NOT NULL ");
					map.put("where", where.toString());
					map.put("order", " order by tg.qqg_update_time desc ");
					map.put("limit", "LIMIT 0,8");
					List<Object> list = goodsService.selectBySelective(map);
					goodsMap.put(RandomUtils.makeUUID(), list);
					tList.addAll(list);
//				}
				icGoodsMap.put(intCategory.getUuid(), goodsMap);
				if (tList.size() > 6) {
					tList = tList.subList(0, 6);
				}
				gjfl.put(intCategory.getUuid(), tList);
			}
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			/*
			
			for (IntCategory intCategory : intCategoryList) {
				icMap.put(intCategory.getUuid(), intCategory.getName());
				goodsMap = new HashMap<>();
				List<Object> tList = new ArrayList();
				// 每个国家的所有商品类型
				categoryList = categoryService.selectByIntCategoryUuid(intCategory.getUuid());
				// 储存每个国家的所有商品类型
				icCategoryMap.put(intCategory.getUuid(), categoryList);
				// 每个国家的每个类型商品只取最新的前8个
				for (Category category : categoryList) {
					where = new StringBuffer();
					// 商品类型
//					where.append("WHERE tg.category_uuid = '" + category.getUuid() + "'");
					// 国家类型
					where.append(" AND tg.int_category_uuid = '" + intCategory.getUuid() + "'");
					// 必须是未删除的且上架的
					where.append(" AND tg.isdeleted = 0 AND tgd.isdeleted = 0 AND status = 1  AND tg.qqg_update_time IS NOT NULL ");
					map.put("where", where.toString());
					map.put("limit", "LIMIT 0,8");
					List<Object> list = goodsService.selectBySelective(map);
					goodsMap.put(category.getUuid(), list);
					tList.addAll(list);
				}
				icGoodsMap.put(intCategory.getUuid(), goodsMap);
				if (tList.size() > 6) {
					tList = tList.subList(0, 5);
				}
				gjfl.put(intCategory.getUuid(), tList);
			}
			*/

			goodsMap = new HashMap<>();

			root.put("home", UrlPath.HOME);

			// 获取全部国家列表
			root.put("intCategoryList", intCategoryList);
			root.put("icCategoryMap", icCategoryMap);
			root.put("icGoodsMap", icGoodsMap);
			root.put("icMap", icMap);
			root.put("gjfl", gjfl);
			adsyhf = getAdvertiseList(3);
			root.put("adsyhf", adsyhf != null && adsyhf.size() > 0 ? adsyhf.get(0) : adsyhf);
			buildHtmlService.buildPage(null, "quanqiugou.html", "quanqiugou.html", root);
			buildHtmlService.buildPage(FolderPath.getMRootPath(), "quanqiugou_m.html", "quanqiugou.html", root);
//			buildHtmlService.buildPage(FolderPath.getMRootPath(), "quanqiugou_m_test.html", "quanqiugou_m_test.html", root);
			this.buildClassMenu(request);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("生成全球购失败：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 获取广告列表
	 * 
	 * @return
	 */
	public List<Advertise> getAdvertiseList(int type) {
		Map<String, Object> map = null;
		StringBuffer where = null;
		List<Advertise> list = null;
		int end = 1;
		// 如果是幻灯片，就查询三条
		if (type == 1) {
			end = 3;
		}
		try {
			map = new HashMap<>();
			where = new StringBuffer();
			map.put("column", "id,uuid,text,photo,path");
			where.append("WHERE ta.isdeleted = 0 ");
			if (type != 0) {
				where.append("AND ta.type = " + type);
			}
			map.put("where", where);
			map.put("order", " ORDER BY ta.createtime DESC");
			map.put("limit", "LIMIT 0," + end);
			list = advertiseService.selectBySelective(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 获取权限
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("getPermCodes.do")
	@ResponseBody
	public Result getPermCode(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Result result = new Result(1, "获取成功");
		String codes = super.getPermCodes();
		result.setData(codes);
		return result;
	}

	/**
	 * 生成商品类型
	 * 
	 * @param request
	 * @return
	 * @throws FileNotFoundException
	 */
	@RequestMapping("buildClassMenu.do")
	@ResponseBody
	public Result buildClassMenu(HttpServletRequest request) throws FileNotFoundException {
		return buildHtmlService.buildClassMenu();
	}


	@RequestMapping("getBuildGoodsPageState.do")
	@ResponseBody
	public Map<String, String> getBuildGoodsPageState() {
		return map;
	}

	@RequestMapping("buildGoodsPage.do")
	@ResponseBody
	public Result buildGoodsPage() {
		final List<String> uuids = goodsService.getAllGoodsUuid();
		synchronized (uuids) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					map.put("code", "1");
					map.put("msg", "商品页正在生成中");
					for (String uuid : uuids) {
						buildHtmlService.buildGoodsPage(uuid);
					}
					map.put("code", "0");
					map.put("msg", "商品页生成完成");
				}
			}).start();
		}
		Result result = new Result(0);
		result.setMsg("商品页正在生成中，稍候完成后我们会通知您");
		return result;
	}

}
